// {isRunning: false, time: 0}
// {isRunning: true, time: 0}
// action.type 可能是

import { useEffect, useReducer } from "react"

//  start/stop/reset/tick
const reducer = (state, action) => {
  console.group('action处理前的state')
  console.log('state:', state)
  console.log('action:', action)
  console.groupEnd()
  switch (action.type) {
    case 'start':
      // 错误写法
      // state.isRunning = true
      // return state
      return { ...state, isRunning: true }
    case 'stop':
      return { ...state, isRunning: false }
    case 'reset':
      return initState(0)
    case 'tick':
      // {isRunning: true, time: 10}
      return { ...state, time: state.time + 1 }
    // {isRunning: true, time: 11}
    default:
      return state
  }
}

function initState(time) {
  return {isRunning: false, time}
}

const Stopwatch = () => {
  const [state, dispatch] = useReducer(reducer, 0, initState)
  console.group('action处理后的state')
  console.log(state)
  console.groupEnd()

  useEffect(() => {
    if (!state.isRunning) {
      return
    }
    const timer = setInterval(
      () => {dispatch({type: 'tick'})}, 1000)

    return () => {
      console.log('清除计时器')
      clearInterval(timer)
    }
  }, [state.isRunning])
  return (
    <div>
      {state.time}秒
      <button onClick={() => dispatch({type: 'start'})}>开始计时</button>
      <button onClick={() => dispatch({type: 'stop'})}>停止计时</button>
      <button onClick={() => dispatch({type: 'reset'})}>重置</button>
    </div>
  )
}

export default Stopwatch
